package cn.jingyuan.owl.web.oauth2;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * 权限
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public final class DefaultAuthority implements GrantedAuthority {

    /** 权限 id */
    @Getter
    @Setter
    private String authorityId;

    /** 权限标识 */
    @Setter
    @Getter
    private String authority;

    /** 过期时间 */
    @Getter
    @Setter
    private Date expireTime;

    /** 权限所有者 */
    @Getter
    @Setter
    private String owner;

    public DefaultAuthority() { }

    public DefaultAuthority(String authority) {
        Assert.hasText(authority, "A granted authority textual representation is required");
        this.authority = authority;
    }

    public DefaultAuthority(String authority, Date expireTime) {
        Assert.hasText(authority, "A granted authority textual representation is required");
        this.authority = authority;
        this.expireTime = expireTime;
    }

    public DefaultAuthority(String authorityId, String authority, Date expireTime, String owner) {
        this.authorityId = authorityId;
        this.authority = authority;
        this.expireTime = expireTime;
        this.owner = owner;
    }

    @JsonProperty("isExpired")
    public Boolean isExpired() {
        return null != expireTime && System.currentTimeMillis() > expireTime.getTime();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else {
            return obj instanceof DefaultAuthority && this.authority.equals(((DefaultAuthority) obj).authority);
        }
    }

    @Override
    public int hashCode() {
        return this.authority.hashCode();
    }

    @Override
    public String toString() {
        return this.authority;
    }

}
